<template>

<el-button type="primary" @click="adds">
    <el-icon><Plus /></el-icon>
    新增
</el-button>
<el-button type="primary" @click="dels" 
  :disabled="ids.length === 0">
    <el-icon><Delete /></el-icon>
    删除
</el-button>

<el-icon @click="refreshPage"><Refresh /></el-icon>
<el-icon @click="showConfigDialog = true"><Setting /></el-icon>

<el-table :data="tableData" border  style="width: 100%;text-align: center" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" fixed="left"/>
    <el-table-column prop="tMid" label="序号" fixed="left"/>
    <el-table-column prop="tmName" label="商品名称" fixed="left" width="150px"/>
    <el-table-column prop="tmBatch" label="生产批次" width="150px"/>
    <el-table-column prop="tmExpiration" label="保质期" width="150px"/>
    <el-table-column prop="tmProduction" label="生产许可号" width="150px"/>
    <el-table-column prop="tmManufacturing" label="生产企业" width="150px"/>
    <el-table-column prop="tmName" label="信息完善度" width="150px"/>
    <el-table-column prop="addName" label="创建人" width="150px"/>
    <el-table-column label="创建时间">
        <template #default="scope">
            {{ scope.row.addDate.substring(0,10) }}
        </template>
    </el-table-column>
    <el-table-column prop="updName" label="修改人" width="150px"/>
    <el-table-column label="操作" fixed="right" width="200px">
        <template #default="scope">
            <el-link type="primary" @click="edit(scope.row)"> 详情</el-link>
            <el-link type="primary" @click="upd(scope.row)"> &nbsp;修改 </el-link>
            <el-link type="primary" @click="dc(scope.row.tmNumber,scope.row.tMid)"> &nbsp;导出溯源码 </el-link>
            <el-link type="primary" @click="del(scope.row.tMid)"> &nbsp;删除 </el-link>
        </template>
    </el-table-column>
  </el-table>
    
  <!-- 添加 -->
  <el-dialog v-model="addshow" title="溯源管理-增加" width="800" 
    @close="handleClose">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="data"
    :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="商品名称" prop="tmName">
      <el-select v-model="data.tmName" placeholder="请选择">
        <el-option v-for="item in goods" :label="item.gName" :value="item.gName" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产批次" prop="tmBatch">
      <el-input v-model="data.tmBatch" />
    </el-form-item>
    <el-form-item label="保质期" prop="tmExpiration">
      <el-input v-model="data.tmExpiration" />
    </el-form-item>
    <el-form-item label="生产许可证号" prop="tmProduction">
      <el-input v-model="data.tmProduction" />
    </el-form-item>
    <el-form-item label="生产企业" prop="tmManufacturing">
      <el-input v-model="data.tmManufacturing" />
    </el-form-item>
    <el-form-item label="封面图" prop="tmImage">
      <el-upload
      class="avatar-uploader"
      :file-list="fileList"
      :action="uploadAction"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
    ><!-- 上传图标 -->
        <el-icon v-if="!data.tmImage" class="avatar-uploader-icon">
          <Plus />
        </el-icon>
        <!-- 显示图片和删除按钮 -->
        <div v-if="data.tmImage" class="avatar-container">
          <img :src="data.tmImage" class="avatar" />
          <el-button class="remove-btn" @click="handleRemove">×</el-button>
        </div>
  </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <!-- 修改 -->
  <el-dialog v-model="updshow" title="溯源管理-修改" width="800" 
    @close="handleClose">
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="data"
    :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="商品名称" prop="tmName">
      <el-select v-model="data.tmName" placeholder="请选择">
        <el-option label="Zone one" value="shanghai" />
        <el-option label="Zone two" value="beijing" />
      </el-select>
    </el-form-item>
    <el-form-item label="生产批次" prop="tmBatch">
      <el-input v-model="data.tmBatch" />
    </el-form-item>
    <el-form-item label="保质期" prop="tmExpiration">
      <el-input v-model="data.tmExpiration" />
    </el-form-item>
    <el-form-item label="生产许可证号" prop="tmProduction">
      <el-input v-model="data.tmProduction" />
    </el-form-item>
    <el-form-item label="生产企业" prop="tmManufacturing">
      <el-input v-model="data.tmManufacturing" />
    </el-form-item>
    <el-form-item label="封面图" prop="tmImage">
      <el-upload
      class="avatar-uploader"
      :file-list="fileList"
      :action="uploadAction"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
    ><!-- 上传图标 -->
        <el-icon v-if="!data.tmImage" class="avatar-uploader-icon">
          <Plus />
        </el-icon>
        <!-- 显示图片和删除按钮 -->
        <div v-if="data.tmImage" class="avatar-container">
          <img :src="data.tmImage" class="avatar" />
          <el-button class="remove-btn" @click="handleRemove">×</el-button>
        </div>
  </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updss(ruleFormRef)">
        修改
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <!-- 导出 -->
  <el-dialog v-model="dcshow" title="导出设置" width="800" >
    <el-form ref="ruleFormRef" style="max-width: 100%;height: 100px" :model="dcdata"
    :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize"
    status-icon >
    <el-form-item label="导出数量" prop="tmNumber">
      <el-input v-model="dcdata.tmNumber" />
    </el-form-item>
    <el-form-item style="float:right;">
      <el-button type="primary" @click="dcs(ruleFormRef)">
        导出
      </el-button>
    </el-form-item>
  </el-form>
  </el-dialog>


  <!-- 列表
  <el-table :data="tableData">
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        v-if="column && column.visible"
        :prop="column.prop"
        :label="column.label">
      </el-table-column>
    </el-table> -->

    <!-- 配置对话框
    <el-dialog title="配置列" :visible.sync="showConfigDialog" width="30%">
      <el-checkbox-group v-model="visibleColumns">
        <el-checkbox v-for="column in columns" :key="column.prop" :label="column.prop">
          {{ column.label }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfig">保存</el-button>
      </span>
    </el-dialog> -->
  

</template>
<script lang="ts" setup>
import{ref,onMounted,reactive,inject } from 'vue'
import { type AxiosStatic } from 'axios';
const axios=inject('axios') as AxiosStatic
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

onMounted(()=>{
    shows()
    xlks()
})

const tableData=ref([])

const shows=()=>{
    axios.get('/TraceManage/GetTraceManages')
    .then((res)=>{
        console.log(res.data)
        tableData.value=res.data
    })
}


const data=reactive({
    tmName:'',
    tmBatch:'',
    tmExpiration:'',
    tmProduction:'',
    tmManufacturing:'',
    addName:'',
    tmImage:''
})
//弹框默认不显示
const addshow=ref(false)
//点击添加显示弹框
const adds=()=>{
    addshow.value=true
}
//关闭弹框清空数据
const handleClose = () => {
  data.tmBatch=""
  data.tmExpiration=""
  data.tmProduction=""
  data.tmManufacturing=""
  data.tmName=""
  data.tmImage=""
};
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//非空
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请选择商品名称', trigger: 'blur' },
  ],
  tmBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { max: 30, message: '生产批次最多支持 30 位字符', trigger: 'blur' }
  ],
  tmExpiration: [
    { required: true, message: '请输入生产保质期', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '只允许输入数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value && value.length > 5) {
        callback(new Error('最多支持输入 5 位数字'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }
  ],
  tmProduction: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/,message: '生产许可证号只能包含字母和数字',trigger: 'blur'},
    { max: 30,message: '生产许可证号最多支持 30 个字符',trigger: 'blur'}
  ],
  tmManufacturing: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { max: 30, message: '生产企业最多支持 30 位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,message: '生产企业只能包含中文字符和字母',trigger: 'blur'}
  ],
  tmImage: [
    { required: true, message: '请上传封面图', trigger: 'blur' },
  ],
  tmNumber: [
    { required: true, message: '导出数量不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '只允许输入数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value && value.length > 4) {
        callback(new Error('最多支持输入 4 位数字'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }
  ],
})
//新增
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        //console.log(data.tmName)
        axios.post('TraceManage/AddTraceManage',{
            tmName: data.tmName,
            tmBatch: data.tmBatch,
            tmExpiration: data.tmExpiration,
            tmProduction: data.tmProduction,
            tmManufacturing: data.tmManufacturing,
            tmImage: data.tmImage,
            addName: "admin",
        })
        .then(res=>{
            console.log(res.data)
            if(res.data>0){
                ElMessage({
                    message: '添加成功',
                    type: 'success',
                })
                addshow.value=false
                shows()
            }else{
                ElMessage({
                    message: '添加失败',
                    type: 'error',
                })
            }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//图片上传
import { ElMessage,ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
const fileList = ref([]);
const uploadAction = ref('http://182.92.209.50:8001/api/TraceManage/GetImage'); // 暂时禁用上传
// 上传成功处理
const handleAvatarSuccess = (file) => {
  // 设置图片 URL
  console.log(file)
  data.tmImage =file;
};

const beforeAvatarUpload = (rawFile) => {
  // 检查文件格式和大小
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2MB!');
    return false;
  }
  if (!['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    ElMessage.error('图片格式错误!');
    return false;
  }
  return true;
};

const handleRemove = () => {
  // 清空图片 URL 和文件列表
  data.tmImage = '';
  fileList.value = [];
  return
};
const ids=ref('')
//获取选中的值
const handleSelectionChange = (val: User[]) => {
    //console.log(val)
    var id='';
    for(var i=0;i<val.length;i++){
        id+=val[i].tMid+',';
        //ids.value=id
    }
    ids.value=id.substring(0,id.length-1)
    console.log(ids.value)
}
//批量删除
const dels=()=>{
  ElMessageBox.confirm(
    '您确定要删除吗?',
    '等待',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      //console.log(ids.value)
      if(ids.value==""){
        ElMessage({
          type: 'error',
          message: '请选择要删除的数据',
        })
        return
      }
      axios.delete('TraceManage/DelT/',{
        params:{
          ids:ids.value,
          names:"admin"
        }
      })
      .then((res)=>{
        console.log(res)
        if(res.data>0){
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          shows()
        }else{
          ElMessage({
            type: 'error',
            message: '删除失败',
          })
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//删除
const del=(id:any)=>{
    ids.value=id
    dels()
}

const updshow=ref(false)

const datas=reactive({
  tMid:"",
  addName:"",
  addDate:"",
  updName:"",
  isDel:""
})
//修改赋值
const upd=(dat:any)=>{
  console.log(dat)
  updshow.value=true
  data.tmBatch=dat.tmBatch
  data.tmName=dat.tmName
  data.tmExpiration=dat.tmExpiration
  data.tmImage=dat.tmImage
  data.tmProduction=dat.tmProduction
  data.tmManufacturing=dat.tmManufacturing

  datas.tMid=dat.tMid
  datas.addName=dat.addName
  datas.addDate=dat.addDate
  datas.isDel=dat.isDel

}

//修改
const updss = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        //console.log(data.tmName)
        axios.post('TraceManage/UpdT',{
            tmName: data.tmName,
            tmBatch: data.tmBatch,
            tmExpiration: data.tmExpiration,
            tmProduction: data.tmProduction,
            tmManufacturing: data.tmManufacturing,
            tmImage: data.tmImage,
            addName: datas.addName,
            addDate:datas.addDate,
            tMid:datas.tMid,
            updName:"admin",
            isDel:datas.isDel
        })
        .then(res=>{
            console.log(res.data)
            if(res.data>0){
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                updshow.value=false
                shows()
            }else{
                ElMessage({
                    message: '修改失败',
                    type: 'error',
                })
            }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}





//导出
const dcshow=ref(false)
const dcdata=reactive({
  tMid:"",
  tmNumber:""
})
//导出
const dc=(number:any,id:any)=>{
  dcshow.value=true
  dcdata.tmNumber=number
  dcdata.tMid=id
}
import QRCode from 'qrcode';
import { saveAs } from 'file-saver';
//导出二维码txt文件
const dcs = async (formEl: FormInstance | undefined) => {
  //console.log(dcdata.tmNumber,dcdata.tMid)
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        //先修改导出数量
        console.log(dcdata.tmNumber,dcdata.tMid)
        axios.post('/TraceManage/GetDc?number='+dcdata.tmNumber+'&tMid='+dcdata.tMid)
        .then(res=>{
            console.log(res.data)
            //修改成功
            if(res.data>0){
            const lis=String(dcdata.tmNumber)
            console.log(lis)

              //   // 生成二维码的 Data URL
              // QRCode.toDataURL(lis).then(qrCodeDataUrl => {
              //   // 提取 Base64 数据部分
              //   const base64Data = qrCodeDataUrl.split(',')[1];
                
              //   // 解码 Base64 数据
              //   const binaryData = atob(base64Data);
              //   const arrayBuffer = new ArrayBuffer(binaryData.length);
              //   const uint8Array = new Uint8Array(arrayBuffer);

              //   for (let i = 0; i < binaryData.length; i++) {
              //     uint8Array[i] = binaryData.charCodeAt(i);
              //   }

              //   // 创建 Blob 并保存为文件
              //   const blob = new Blob([uint8Array], { type: 'image/png' }); // 使用 image/png 类型
              //   saveAs(blob, 'qrcode.png'); // 保存为 PNG 文件
              // }).catch(error => {
              //   console.error('Error generating QR code:', error);
              // });

              // 生成二维码的 Data URL
              QRCode.toDataURL(lis).then(qrCodeDataUrl => {
                // 提取 Base64 数据部分
                const base64Data = qrCodeDataUrl.split(',')[1];
                
                // 将 Base64 数据作为文本保存
                const textBlob = new Blob([base64Data], { type: 'text/plain' });
                saveAs(textBlob, 'qrcode.txt'); // 保存为 TXT 文件
              }).catch(error => {
                console.error('Error generating QR code:', error);
              });


                ElMessage({
                    message: '导出成功',
                    type: 'success',
                })
              //关闭弹框
                dcshow.value=false
                shows()
            }else{
                ElMessage({
                    message: '导出失败',
                    type: 'error',
                })
            }
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//刷新页面
const refreshPage=()=> {
      // 刷新页面
      window.location.reload();
    }

// // 控制对话框的显示与隐藏
// const showConfigDialog = ref(false);

// // 列的配置
// const columns = ref([
//   { prop: 'tmName', label: '商品名称', visible: true },
//   { prop: 'tMid', label: '序号', visible: true },
// ]);

// // 用户选择的可见列
// const visibleColumns = ref(columns.value.filter(col => col.visible).map(col => col.prop));


// // 保存配置
// function saveConfig() {
//   columns.value.forEach(column => {
//     column.visible = visibleColumns.value.includes(column.prop);
//   });
//   showConfigDialog.value = false;
// }




const goods=ref([])
//商品下拉框
const xlks=()=>{
  axios.get('Goods/GetGoodsxlk')
  .then(res=>{
    goods.value=res.data
  })
}
//跳转详情页
import { useRouter } from 'vue-router'
const router = useRouter()
const edit=(id:any)=>{
  localStorage.setItem('tmid',id.tMid);
  localStorage.setItem('pc',id.tmBatch);
  localStorage.setItem('sc',id.tmProduction);
  router.push({
    path:'/RabbitInfo',
    query:{
      id:id.tMid
    }
  })
}





</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-container {
  position: relative;
  width: 178px;
  height: 178px;
}

.remove-btn {
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 24px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10; /* 确保按钮在图片上层 */
}

.remove-btn:hover {
  background-color: rgba(0, 0, 0, 0.8);
}
</style>